<script setup lang="ts">
import {ref, onMounted, nextTick} from "vue";
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermission,
  reqRemoveRole
} from '@/api/acl/role/index.ts'
import type {RoleResponseData,Records,RoleData,MenuResponseData,MenuList} from '@/api/acl/role/type.ts'
import useLayOutSettingStore from "@/store/modules/setting.ts";
import {ElMessage} from "element-plus";
const pageNo= ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)
const keyWord = ref<string>('')
const allRole = ref<Records>([])
/**
 * 获取职位信息
 * @param pager
 */
const getRole = async (pager=1) => {
  pageNo.value=pager
  const res:RoleResponseData = await reqAllRoleList(pageNo.value,pageSize.value,keyWord.value)
  if(res.code==200){
    total.value=res.data.total
    allRole.value=res.data.records
  }
  // console.log(res)
}
onMounted(()=>{
  getRole()
})
/**
 * 页数改变
 */
const changePageSize = () => {
  getRole()
}
/**
 * 搜索
 */
const search = () => {
  getRole()
  keyWord.value=''
}
//布局store用于重置刷新
const layOutSettingStore=useLayOutSettingStore()
/**
 * 重置
 */
const reset = () => {
  layOutSettingStore.refresh=!layOutSettingStore.refresh
}
const roleEditDialogVisible = ref<boolean>(false)
const roleParams= ref<RoleData>({
  createTime: "", remark: "", updateTime: "", id: '', roleName: ''
})
/**
 * 编辑职位
 */
const editRole = async (row:RoleData) => {
  if(row.id){Object.assign(roleParams.value,row)}
  roleEditDialogVisible.value=true
  await nextTick(() => {
    form.value?.clearValidate('roleName')
  })
}
/**
 * 自定义校验规则
 * @param rules
 * @param value
 * @param callBack
 */
const validateRoleName = (_:any,value:any,callBack:any) => {
  if(value&&value.trim().length>=2){
    callBack()
  }else {
    callBack(new Error('字符长度必须大于2'))
  }
}
const rules ={
  roleName:[{required:true,trigger:'blur',validator:validateRoleName}]
}
//表单组件实例
const form = ref<any>()
/**
 *保存职位
 */
const save = async () => {
  await form.value.validate()
  const res:any= await reqAddOrUpdateRole(roleParams.value)
  if(res.code==200){
    ElMessage({type:'success',message:roleParams.value.id?'修改成功':'添加成功'})
    roleEditDialogVisible.value = false
    await getRole(roleParams.value.id?pageNo.value:1)
  }
  Object.assign(roleParams.value,{createTime: "", remark: "", updateTime: "", id: '', roleName: ''})
  // console.log(res)
}
//控制抽屉显示
const drawer = ref<boolean>(false)
//筛选后的被选中数组的ID
const selectArr = ref<number[]>([])
//权限菜单
const menuArr = ref<MenuList>([])
/**
 * 筛选默认被选中的节点的ID
 * @param allData
 * @param initArr
 */
const filterSelectArr = (allData:any,initArr:any) => {
  allData.forEach((item:any)=>{
    if(item.select&&item.level==4){
      initArr.push(item.id)
    }
    if(item.children&&item.children.length>0){
      filterSelectArr (item.children,initArr)
    }
  })
  return initArr
}
/**
 * 设置权限按钮
 */
const setPermission = async (row:RoleData) => {
  Object.assign(roleParams.value,row)
  const res:MenuResponseData = await reqAllMenuList(row.id as number)
  if(res.code==200){
    menuArr.value=res.data
    selectArr.value = await filterSelectArr(menuArr.value,[])
  }
  drawer.value=true
}
//树形结构属性名绑定
const defaultProps = {
  children: 'children',
  label: 'name',
}
//树结构组件实例
const tree= ref<any>()
/**
 * 分配角色
 */
const handler = async () => {
  const roleId =roleParams.value.id
  const arr = tree.value.getCheckedKeys()//选中节点的ID
  const arr1=tree.value.getHalfCheckedKeys()//半选的ID
  const permissionId = arr.concat(arr1)
  console.log(arr,arr1)
  const res:any = await reqSetPermission(roleId as number,permissionId)
  if(res.code==200){
    drawer.value = false
    ElMessage({type:'success',message:'分配角色成功'})
    window.location.reload()
  }
}
/**
 * 删除角色
 * @param roleId
 */
const removeRole = async (roleId:number) => {
  const res = await reqRemoveRole(roleId)
  if(res.code==200){
    ElMessage({type:'success',message:'删除成功'})
  }
  await getRole(allRole.value.length>1?pageNo.value:pageNo.value-1)
}
</script>

<template>
  <el-drawer v-model="drawer">
    <template #header>
      <span>分配权限</span>
    </template>
    <template #default>
      <el-tree
          :data="menuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectArr"
          :props="defaultProps"
          ref="tree"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer=false">取消</el-button>
        <el-button type="primary" @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <el-card>
    <el-form inline class="form">
      <el-form-item label="职位搜索：">
        <el-input placeholder="请你输入搜索的职位" v-model="keyWord" ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!keyWord" @click="search">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin-top: 10px;">
    <el-button type="primary" icon="Plus" @click="editRole">添加职位</el-button>
    <el-table border style="margin-top: 10px;" :data="allRole">
      <el-table-column  align="center" type="index"></el-table-column>
      <el-table-column  align="center" label="ID" prop="id"></el-table-column>
      <el-table-column  align="center" show-overflow-tooltip label="职位名称" prop="roleName"></el-table-column>
      <el-table-column  align="center" show-overflow-tooltip label="创建时间" prop="createTime"></el-table-column>
      <el-table-column  align="center" show-overflow-tooltip label="更新时间" prop="updateTime"></el-table-column>
      <el-table-column  align="center" label="操作" width="300px">
        <template #default="{row}">
          <el-button size="small" type="primary" icon="User" @click="setPermission(row)">分配权限</el-button>
          <el-button size="small" type="success" icon="Edit" @click="editRole(row)">编辑</el-button>
          <el-popconfirm :title="`你确定要删除${row.roleName}吗？`" @confirm="removeRole(row.id)">
            <template #reference>
              <el-button size="small" type="danger" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[10,12,14,16]"
        :disabled="false"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        style="margin-top: 15px"
        @current-change="getRole"
        @size-change="changePageSize"
    />
  </el-card>
  <el-dialog
      v-model="roleEditDialogVisible"
      :title="roleParams.id?'更新职位':'添加职位'"
      width="50%"
  >
    <el-form :model="roleParams" :rules="rules" ref="form">
      <el-form-item label="职位名称：" prop="roleName">
        <el-input placeholder="请输入职务名称" v-model="roleParams.roleName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="roleEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.form{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>